package com.tyc.log.comtroller;

import com.tyc.log.logger.DataLogger;
import com.tyc.log.logger.TraceLogger;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.MDC;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.concurrent.TimeUnit;

/**
 * 类描述
 *
 * @author tyc
 * @version 1.0
 * @date 2022-12-26 16:14:17
 */
@RestController
@RequestMapping("test")
@Slf4j
public class TestController {
    @Autowired
    private ThreadPoolTaskExecutor commonExecutor;

    @PostMapping("/order")
    public void createOrder(){
        checkParams();
        saveOrder();
    }

    @PostMapping("/register")
    public void register(){
        // todo 利用AOP 降低日志与业务代码耦合
        TraceLogger.info("register start");
        checkParams();
        commonExecutor.execute(()->{
            sendMsg();
            TraceLogger.info("sendMsg end");
        });
        commonExecutor.execute(()->{
            sendReward();
            TraceLogger.info("sendReward end");
        });
        saveUser();
        TraceLogger.info("register end");
        // 数据打点
        // todo 可用canal来代替 降低日志与业务代码耦合
        DataLogger.info("order","{name:'张三',orderId:123}");
        log.error("error.................");
    }

    /**
     * 发放奖励
     */
    private void sendReward() {
        try {
            TimeUnit.MILLISECONDS.sleep(50);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    /**
     * 发送信息
     */
    private void sendMsg() {
        try {
            TimeUnit.MILLISECONDS.sleep(100);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    /**
     * 保存到数据库
     */
    private void saveUser() {
        try {
            TimeUnit.MILLISECONDS.sleep(500);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    private void saveData() {

    }

    private void saveOrder() {
        try {
            TimeUnit.MILLISECONDS.sleep(500);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    /**
     * 检验参数
     */
    private void checkParams() {
        try {
            TimeUnit.MILLISECONDS.sleep(30);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
